import {Component, Input, OnInit} from "@angular/core";
import {ActionSheetController, AlertController} from "ionic-angular";
import {Storage} from "@ionic/storage";
import {Common} from "../../../providers/common";
import _ from "lodash";

import {MarketingMobileService} from "./mobile.service";

@Component({
    selector: "page-marketing-mobile",
    templateUrl: "./mobile.html",
    providers: [MarketingMobileService]
})
export class MarketingMobilePage {
    moa_page_name: any = "page-marketing-mobile";
    moa_page_explain: any = "经营分析";

    userId: string
    analysisResult: any[] = []
    isAdmin: boolean = false
    dataState: number = 0 //0表示加载中，1表示有数据，2表示无数据
    orgSheet: any[] = []
    isShowSheet: boolean = false
    currDisplay: number = 0 //0表示全部，10表示北分，20表示上分，30表示广分，40表示渠道总部
    currOrg: any = {
        id: 0,
        name: "全部",
        select: true
    };

    hasOpAuth = false;

    constructor(
        private actionSheetCtrl: ActionSheetController,
        private storage: Storage,
        private marketingMobileService: MarketingMobileService,
        private alertCtrl: AlertController,
        private common: Common
    ) {}
    ionViewDidEnter(): void {
        let loginid: string,
            org: string;
        this.storage.get("userInfo").then(user => {
            loginid = user.loginid;
            org = user.orgname;
            this.marketingMobileService.getUSPMobileData(loginid).subscribe((res: any) => {
              this.hasOpAuth = res.isAdmin;
              if (res.requestData) {
                this.dealMobileData(res.requestData, org);
              }
            });
        });
    }

    dealMobileData(res, org) {
      this.orgSheet = [];
      this.analysisResult = [];
      if (res.data && res.data.length > 0) {
        this.dataState = 1;
        /***Start****/
        console.log("服务器相应的数据：", res);
        //获取分析数据
        res.data.forEach((v: any) => {
          if (v.data) this.analysisResult.push(v);
        });
        //判断是否为管理员
        this.isAdmin = this.judgeAdmin(res.organization, org);
        //创建操作表子项
        const orgs = res.organization;
        orgs.unshift({
          id: 0,
          name: "全部",
          select: true
        });
        orgs.push({
          id: null,
          name: "取消",
          select: true
        });
        orgs.forEach((v: any, i: number) => {
          if (v.select) {
            let item: any = {
              text: v.name,
              role: i === orgs.length - 1 ? "cancel" : "destructive",
              handler: () => {
                if (i !== orgs.length - 1) {
                  this.currOrg = v;
                };
                this.isShowSheet = !this.isShowSheet;
                console.log(this.currOrg);
              }
            };
            this.orgSheet.push(item);
          }
        });
        /***End****/
        console.log("分析数据：", this.analysisResult);
        console.log("管理员", this.isAdmin);
      } else {
        this.dataState = 2;
      }
    }

    selectDep(): void {
        if (!this.isAdmin) return;
        this.isShowSheet = !this.isShowSheet;
        let actionSheet = this.actionSheetCtrl.create({
            title: "请选择需要查看的部门",
            buttons: this.orgSheet
        });
        actionSheet.present();
    }
    judgeAdmin(dpm: any[], org: string): boolean {
        let item = dpm.find((v: any) => {
                if (v.name === org) return v;
            }),
            result = item ? false : true;
        return result;
    }
    judgeOrg(dpm: any[], orgId: number): boolean {
        if (orgId === 0) return true;
        let item = dpm.find((v: any) => {
                if (orgId === +v.l_order_no) return v;
            }),
            result = item ? true : false;
        return result;
    }
    setBgClolor(orgId: string): string {
		if (this.currOrg.id > 0) return "bg-red";
        return +orgId % 20 === 10 ? "bg-red" : "bg-blue";
    }

  moreOp() {
    let bottons = [{
      text: '生成',
      handler: () => {
        this.storage.get("userInfo").then(user => {
          let loginid = user.loginid;
          let org = user.orgname;
          this.marketingMobileService.generateUSBMobileData(loginid).subscribe((res: any) => {
            if (res) {
              if (res.isSuccess) {
                this.common.alertMessage("数据生成成功！");
                this.dealMobileData(res.requestData, org);
              } else {
                this.common.alertMessage("数据生成失败！");
              }
            }
          });
        });
      }
    }, {
      text: '发布',
      handler: () => {
        let confirm = this.alertCtrl.create({
          title: '提示',
          message: "您确定要发布吗？",
          enableBackdropDismiss: false,
          buttons: [{
            text: '取消',
            role: 'cancel',
            handler: () => {

            }
          }, {
            text: '确定',
            handler: () => {
              this.storage.get("userInfo").then(user => {
                let loginid = user.loginid;
                let org = user.orgname;
                this.marketingMobileService.publishUSBMobileData().subscribe((res: any) => {
                  if (res) {
                    if (res.isSuccess) {
                      this.common.alertMessage("数据发布成功！");
                      this.dealMobileData(res.requestData, org);
                    } else {
                      this.common.alertMessage("数据发布失败！");
                    }
                  }
                });
              });
            }
          }]
        });
        confirm.present();
      }
    }, {
      text: '回滚',
      handler: () => {
        let confirm = this.alertCtrl.create({
          title: '提示',
          message: "您确定要回滚吗？",
          enableBackdropDismiss: false,
          buttons: [{
            text: '取消',
            role: 'cancel',
            handler: () => {

            }
          }, {
            text: '确定',
            handler: () => {
              this.storage.get("userInfo").then(user => {
                let loginid = user.loginid;
                let org = user.orgname;
                this.marketingMobileService.rollBackUSBMobileData().subscribe((res: any) => {
                  if (res) {
                    if (res.isSuccess) {
                      this.common.alertMessage("数据回滚成功！");
                      this.dealMobileData(res.requestData, org);
                    } else {
                      this.common.alertMessage("数据回滚失败！");
                    }
                  }
                });
              });
            }
          }]
        });
        confirm.present();
      }
    }, {
      text: '取消',
      role: 'cancel',
      handler: () => {
      }
    }];

    let actionSheet = this.actionSheetCtrl.create({
      title: '',
      buttons: bottons
    });
    actionSheet.present();
  }

}

@Component({
    selector: "trend",
    template: "<span [ngClass]='color'>{{arrow}}{{amount}}</span>"
})
export class TrendComponent implements OnInit {
    @Input() isArrow: boolean
    @Input() amount: any
    color: string
    arrow: string
    ngOnInit(): void {
      console.log(typeof this.amount, " ", this.amount);
        this.color = Number(this.amount) > 0 ? "rise" : "fall";
        let temp = _.toString(this.amount).split(".");
        let r = 0;
        if (temp && temp[1]) {
          r = temp[1].length;
        }
        if (this.isArrow) {
            this.arrow = Number(this.amount) > 0 ? "↑" : "↓";
            this.amount = parseFloat(_.toString(Math.abs(this.amount))).toFixed(r);
            console.log(typeof this.amount, " ", this.amount, " r:", r);
        }
    }
}

@Component({
    selector: "end-symbol",
    template: "<span>{{endSymbol}}</span>"
})
export class EndSymbolComponent implements OnInit {
    @Input() length: number
    @Input() index: number
    endSymbol: string
    ngOnInit(): void {
        this.endSymbol = this.index < this.length - 1 ? "；" : "。";
    }
}
